import tinymce from 'tinymce/tinymce'
import onAnnexTitleChange from './annexTitleChange'
import onListTitleChange from './listTitleChange'
import onKeywordChange from './keywordChange'
import onUpdateFormulaNumber from './updateFormulaNumber'
import onUpdateIndex from './updateIndex'
import onUpdateRef from './updateRef'
import onPageChange from './pageChange'
import onTermsChange from './termsChange'
import addDocContent from './addDocContent'

export default function registerEvents(editor) {
  addListener(editor)
  onAnnexTitleChange(editor)
  onListTitleChange(editor)
  onKeywordChange(editor)
  onUpdateFormulaNumber(editor)
  onUpdateIndex(editor)
  onUpdateRef(editor)
  onPageChange(editor)
  onTermsChange(editor)
  addDocContent(editor)
}

function addListener(editor) {
  editor.dom.select('#tinymce>.page-wrapper [contenteditable="true"]').forEach((node) => {
    node.addEventListener('input', (e) => {
      if (tinymce.DOM.is(e?.target, '.list-title')) {
        editor.fire('listTitleChange')
      }

      if (tinymce.DOM.is(e?.target, '.annex-title')) {
        editor.fire('annexTitleChange')
      }
      e.stopPropagation()
    })
  })
}
